<?php

namespace app\services;

use support\Cache;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

class CaptchaService
{
    /**
     * 获取验证码
     * @param string $account
     * @param string $scenario
     * @return string Captcha image content
     */
    public static function getCaptcha(string $account, string $scenario): string
    {
        $key = self::generateKey($account, $scenario, 'captcha');
        $builder = new PhraseBuilder(4, 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ');
        $captcha = new CaptchaBuilder(null, $builder);
        $captcha->build(120);

        // Store captcha value in cache (valid for 5 minutes)
        Cache::set($key, strtolower($captcha->getPhrase()), 300);

        // Return captcha image content
        return $captcha->inline();
    }

    /**
     * 校验验证码
     * @param string $account
     * @param string $scenario
     * @param string $captcha
     * @return string Operation token
     * @throws \Exception
     */
    public static function validateCaptcha(string $account, string $scenario, string $captcha): string
    {
        $captchaKey = self::generateKey($account, $scenario, 'captcha');
        $cachedCaptcha = Cache::get($captchaKey);

        if (!$cachedCaptcha || strtolower($captcha) !== $cachedCaptcha) {
            throw new \Exception('验证码错误或已过期');
        }

        // Remove captcha from cache after validation
        Cache::delete($captchaKey);

        // Generate operation token
        $tokenKey = self::generateKey($account, $scenario, 'token');
        $token = bin2hex(random_bytes(16));

        // Store token in cache (valid for 10 minutes)
        Cache::set($tokenKey, $token, 600);

        return $token;
    }

    /**
     * 校验令牌
     * @param string $account
     * @param string $scenario
     * @param string $token
     * @return bool
     */
    public static function validateToken(string $account, string $scenario, string $token): bool
    {
        $tokenKey = self::generateKey($account, $scenario, 'token');
        $cachedToken = Cache::get($tokenKey);

        return $cachedToken === $token;
    }

    /**
     * 生成缓存键
     * @param string $account
     * @param string $scenario
     * @param string $type
     * @return string
     */
    private static function generateKey(string $account, string $scenario, string $type): string
    {
        return "captcha_service:{$type}:{$account}:{$scenario}";
    }
}